import axios from "axios";
import {
	ElNotification
} from 'element-plus'
import router from '../router'
import {
	getCookie
} from "./cookie";

axios.defaults.withCredentials = true

// 请求拦截器(头部携带token)
axios.interceptors.request.use(config => {
	let token = getCookie("lrv-etonegg");
	config.headers['Authorization'] = token;
	return config
}, error => {
	console.log(error);
})

//请求token的后置拦截（对token过期，错误等统一处理）
axios.interceptors.response.use(response => {
	let res = response.data;
	//请求正确
	//token过期
	if (response.status == "4001") {
		ElNotification({
			title: "您未登录",
			type: 'warning',
		});
		router.replace("/login")
	}
	//token错误
	if (res.code == "any") {
		ElNotification({
			title: res.message,
			type: 'warning',
		});
		router.replace("/login")
	}
	//除了token错误，其他都正常返回
	else {
		return response
	}

}, )

// let base = 'http://175.178.9.184:8848';
let base = 'http://localhost:8785/api';
//传递json的post请求
export const postRequest = (url, params) => {
	return axios({
		method: 'post',
		url: `${base}${url}`,
		data: params,
		headers: {
			'Authorization': getCookie("token"),
		},
		xhrFields: {
			withCredentials: true // 这里设置了withCredentials
		},


	})
}
//传递json的put请求
export const putRequest = (url, params) => {
	return axios({
		method: 'put',
		url: `${base}${url}`,
		data: params,
		xhrFields: {
			withCredentials: true // 这里设置了withCredentials
		}

	})
}
//传递json的get请求
export const getRequest = (url, params) => {
	return axios({
		method: 'get',
		url: `${base}${url}`,
		data: params,
		xhrFields: {
			withCredentials: true // 这里设置了withCredentials
		}

	})
}
//传递json的delete请求
export const deleteRequest = (url, params) => {
	return axios({
		method: 'delete',
		url: `${base}${url}`,
		data: params,
		xhrFields: {
			withCredentials: true // 这里设置了withCredentials
		}

	})
}
